#!/bin/bash
__SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
if [ ! -e "$__SCRIPT_DIR/utils.sh" ]
then
    echo "[ERR] $__SCRIPT_DIR/utils.sh not found"
    exit -1
fi

source "$__SCRIPT_DIR/utils.sh"

function main() {
    problem_name=${_PROBLEM_NAME// /_}
    problem_name=${problem_name%/}
    find . -type l -exec rm -v {} \;
    if [ -n "$problem_name" ]
    then
        if [[ $_LANG == c++ ]]; then
            _main=Main.cpp
            _c_solution=$(find "$problem_name/c++" -name ${_SOLUTION_BASENAME}.cpp)
            if [ -z "$_c_solution" ]
            then
                echo -e "$CWARN $problem_name/c++/${_SOLUTION_BASENAME}.cpp not found"
            fi
            ln -s "$_c_solution" $_main
        fi
        if [[ $_LANG == python ]]; then
            _main=Main.py
            _py_solution=$(find "$problem_name/python" -name ${_SOLUTION_BASENAME}.py)
            if [ -z "$_py_solution" ]
            then
                echo -e "$CWARN $problem_name/python/${_SOLUTION_BASENAME}.py not found"
            fi
            ln -s "$_py_solution" $_main
        fi
        if [[ $_LANG == golang ]]; then
            _main=Main.go
            _main_test=Main_test.go
            _go_solution=$(find "$problem_name/golang" -name ${_SOLUTION_BASENAME}.go)
            if [ -z "$_go_solution" ]
            then
                echo -e "$CWARN $problem_name/golang/${_SOLUTION_BASENAME}.go not found"
            fi
            ln -s "$_go_solution" $_main
            _go_test=$(find "$problem_name/golang" -name ${_SOLUTION_BASENAME}_test.go)
            if [ -z "$_go_test" ]
            then
                echo -e "$CWARN $problem_name/golang/${_SOLUTION_BASENAME}_test.go not found"
            fi
            ln -s "$_go_test" $_main_test
        fi
        find . -type l -name "Main*" -exec ls -l {} \;
    fi
}

_PROBLEM_NAME="$1"
if [ -z "$_PROBLEM_NAME" ]
then
    echo "Usage: $0 <PROBLEM NAME>"
    echo "  e.g. $0 1._Two_Sum"
    exit -1
fi

_LANG="${2:-c++}"
_max_try=3
_try=0
while [[ $_try -lt $_max_try ]]
do
    if \
[ "$_LANG" == "c++" ] || \
[ "$_LANG" == "python" ] || \
[ "$_LANG" == "golang" ]
    then
        break
    fi
    read -p "'$_LANG' is not support. Re-type: " _LANG
    let _try++
    if [[ $_try -eq $_max_try ]]
    then
        die "reach max try ($_max_try). Exit."
    fi
done

main
